package cn.com.digitalnet.ad.util;


import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
 
public class SolrDocsUtils {
     
     
    public static  Object toBean( SolrDocument record , Class clazz) throws Exception{
             
         Object o = null;
        try {
            o = clazz.newInstance();
        } catch (InstantiationException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IllegalAccessException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
         Field[] fields =   clazz.getDeclaredFields();
         for(Field field:fields){
        	 Object value = null;
        	 if(!Modifier.isStatic(field.getModifiers())){
        		 
        		 value = record.get(field.getName());
                 Class type = field.getType();
                 field.getModifiers();
                 if(type==Long.class && value!=null){
                	value=Long.parseLong((String) value);
                 }
                 try {
                	
//                    BeanUtils.setProperty(o, field.getName(), value);
                    PropertyUtils.setProperty(o, field.getName(), value);
                } catch (IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        	 }

         }
        return o;
    }
     
    public static List toBeanList(SolrDocumentList records, Class  clazz) throws Exception{
        List  list = new ArrayList();
        for(SolrDocument record : records){
            list.add(toBean(record,clazz));
        }
        return list;
    }
 
}